package com.intxt.bbs.controller;

import java.util.List;

import com.intxt.bbs.interceptor.UserLoginInterceptor;
import com.intxt.bbs.model.Link;
import com.intxt.bbs.model.User;
import com.intxt.bbs.service.LinkService;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

@Before(UserLoginInterceptor.class)
public class LinkController extends Controller {
	private static final LinkService USER_LINK_SERVICE = new LinkService();
	
	public void index(){
		User u  = (User)getSession().getAttribute("user");
		if(u!=null){
			String uid = u.getStr("id");
			List<Link> userLinks = USER_LINK_SERVICE.findUserLink(uid);
			setAttr("userLinks", userLinks);
		}	
		List<Link> systemLinks = USER_LINK_SERVICE.findSystemLink();
		getSession().setAttribute("systemLinks", systemLinks);

		render("/user/link.jsp");
	}
	
	public void saveOrUpdateLink(){
		String userId = ((User)getSession().getAttribute("user")).getStr("id");
		String name = getPara("name");
		String url = getPara("url");
		String head = getPara("head");
		String linkId = getPara("linkId");
		String weight = getPara("weight");
		Link link = new Link();
		link.set("name", name);
		link.set("weight", weight);
		if(url.startsWith("https://") || url.startsWith("http://")){
			link.set("url", url);
		}else{
			link.set("url", head+url);
		}
		if(StrKit.notBlank(linkId)){
			link.set("id", linkId);
			USER_LINK_SERVICE.updae(link);
			redirect("/link");
			return;
		}
		link.set("user_id", userId);
		USER_LINK_SERVICE.save(link);
		redirect("/link");
	}
	
	public void delLink(){
		String linkId = getPara("linkId");
		USER_LINK_SERVICE.del(new Link().set("id", linkId));
		redirect("/link");
	}
}
